<template>
  <div class="orders-list">
    <n-card title="我的订单" class="list-card">
      <n-data-table
        :columns="columns"
        :data="orders"
        :loading="loading"
        :pagination="pagination"
        @update:page="handlePageChange"
      />
    </n-card>

    <!-- 退款对话框 -->
    <n-modal v-model:show="showRefundModal" preset="dialog" title="申请退款">
      <template #content>
        <n-form
          ref="formRef"
          :model="refundForm"
          :rules="refundRules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
        >
          <n-form-item label="退款原因" path="reason">
            <n-input
              v-model:value="refundForm.reason"
              type="textarea"
              placeholder="请输入退款原因"
              :rows="3"
            />
          </n-form-item>
        </n-form>
      </template>
      <template #action>
        <n-space justify="end">
          <n-button @click="showRefundModal = false">
            取消
          </n-button>
          <n-button type="primary" :loading="refundLoading" @click="handleRefundSubmit">
            提交
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { h, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { getOrderList, refundPayment } from '@/api/payment'
import { formatDate } from '@/utils/format'

const router = useRouter()
const message = useMessage()

const loading = ref(false)
const orders = ref([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 40]
})

// 退款相关
const showRefundModal = ref(false)
const refundLoading = ref(false)
const currentOrderNo = ref('')
const refundForm = ref({
  reason: ''
})
const refundRules = {
  reason: {
    required: true,
    message: '请输入退款原因',
    trigger: 'blur'
  }
}

// 表格列定义
const columns = [
  {
    title: '订单号',
    key: 'orderNo',
    width: 180
  },
  {
    title: '服务类型',
    key: 'serviceType',
    width: 120
  },
  {
    title: '金额',
    key: 'amount',
    width: 100,
    render(row) {
      return h('span', null, `¥ ${row.amount}`)
    }
  },
  {
    title: '订单状态',
    key: 'status',
    width: 100,
    render(row) {
      const statusMap = {
        'PENDING': { type: 'warning', text: '待支付' },
        'PAID': { type: 'success', text: '已支付' },
        'CANCELLED': { type: 'error', text: '已取消' }
      }
      const status = statusMap[row.status] || { type: 'default', text: row.status }
      return h('n-tag', { type: status.type }, { default: () => status.text })
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return h('span', null, formatDate(row.createTime))
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render(row) {
      const actions = []

      // 查看详情
      actions.push(
        h('n-button', {
          text: true,
          type: 'primary',
          onClick: () => handleViewDetail(row.orderNo)
        }, { default: () => '查看' })
      )

      // 待支付状态可以去支付
      if (row.status === 'PENDING') {
        actions.push(
          h('n-button', {
            text: true,
            type: 'primary',
            onClick: () => handlePayment(row.orderNo)
          }, { default: () => '去支付' })
        )
      }

      // 已支付状态可以申请退款
      if (row.status === 'PAID') {
        actions.push(
          h('n-button', {
            text: true,
            type: 'error',
            onClick: () => handleRefund(row.orderNo)
          }, { default: () => '退款' })
        )
      }

      return h('n-space', null, { default: () => actions })
    }
  }
]

// 获取订单列表
const getOrders = async () => {
  try {
    loading.value = true
    const res = await getOrderList({
      pageNum: pagination.page,
      pageSize: pagination.pageSize
    })
    if (res.code === 0) {
      orders.value = res.data.records
      pagination.itemCount = res.data.total
    }
  } catch (error) {
    message.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handlePageChange = (page) => {
  pagination.page = page
  getOrders()
}

// 查看订单详情
const handleViewDetail = (orderNo) => {
  router.push(`/payment/confirm/${orderNo}`)
}

// 去支付
const handlePayment = (orderNo) => {
  router.push(`/payment/confirm/${orderNo}`)
}

// 申请退款
const handleRefund = (orderNo) => {
  currentOrderNo.value = orderNo
  refundForm.value.reason = ''
  showRefundModal.value = true
}

// 提交退款申请
const handleRefundSubmit = async () => {
  if (!refundForm.value.reason) {
    message.warning('请输入退款原因')
    return
  }

  try {
    refundLoading.value = true
    const res = await refundPayment(currentOrderNo.value, refundForm.value.reason)
    if (res.code === 0) {
      message.success('退款申请已提交')
      showRefundModal.value = false
      getOrders()
    } else {
      message.error(res.message || '退款申请失败')
    }
  } catch (error) {
    message.error('退款申请失败')
  } finally {
    refundLoading.value = false
  }
}

// 初始化
getOrders()
</script>

<style scoped>
.orders-list {
  padding: 20px;
}

.list-card {
  margin-bottom: 20px;
}
</style>
